/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package peterka.ecka.commons;

/**
 *
 * @author mpeterka
 */
public class Utils {

    private Utils() {
        // only static
    }

    public static String[] split(String sb, String splitter) {
        String[] strs = new String[sb.length()];
        int splitterLength = splitter.length();
        int initialIndex = 0;
        int indexOfSplitter = indexOf(sb, splitter, initialIndex);
        int count = 0;
        if (-1 == indexOfSplitter) {
            return new String[]{sb.toString()};
        }
        while (-1 != indexOfSplitter) {
            char[] chars = new char[indexOfSplitter - initialIndex];
            sb.getChars(initialIndex, indexOfSplitter, chars, 0);
            initialIndex = indexOfSplitter + splitterLength;
            indexOfSplitter = indexOf(sb, splitter, indexOfSplitter + 1);
            strs[count] = new String(chars);
            count++;
        }
        // get the remaining chars.
        if (initialIndex + splitterLength <= sb.length()) {
            char[] chars = new char[sb.length() - initialIndex];
            sb.getChars(initialIndex, sb.length(), chars, 0);
            strs[count] = new String(chars);
            count++;
        }
        String[] result = new String[count];
        /*
        for (int i = 0; i < count; i++) {
        result[i] = strs[i];
        }
         */
        System.arraycopy(strs, 0, result, 0, count);
        return result;
    }

    public static int indexOf(String sb, String str, int start) {
        int index = -1;
        if ((start >= sb.length() || start < -1) || str.length() <= 0) {
            return index;
        }
        char[] tofind = str.toCharArray();
        outer:
        for (; start < sb.length(); start++) {
            char c = sb.charAt(start);
            if (c == tofind[0]) {
                if (1 == tofind.length) {
                    return start;
                }
                inner:
                for (int i = 1; i < tofind.length; i++) { // start on the 2nd character
                    char find = tofind[i];
                    int currentSourceIndex = start + i;
                    if (currentSourceIndex < sb.length()) {
                        char source = sb.charAt(start + i);
                        if (find == source) {
                            if (i == tofind.length - 1) {
                                return start;
                            }
                            continue inner;
                        } else {
                            start++;
                            continue outer;
                        }
                    } else {
                        return -1;
                    }

                }
            }
        }
        return index;
    }
}
